/*
 * @Author: 江舟 jijiangzhou@recycloud.cn
 * @Date: 2024-03-22 17:25:12
 * @LastEditors: 江舟 jijiangzhou@recycloud.cn
 * @LastEditTime: 2024-04-29 09:56:58
 * @FilePath: \vite-project\src\components\common\CommonModal.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { Button, Form, Modal, Space, type ModalProps } from 'antd';
import React, { useEffect, useState, useImperativeHandle, forwardRef } from 'react';

interface CommonModalProps {
	close?: () => void;
	onSubmit?: (form?: any, callback?: () => void, modalCallback?: () => void) => void;
	initFormData?: any;
	width?: number;
	formSetting?: any;
	hideFooter?: boolean;
	submitDraft?: boolean;
	hideSubmit?: boolean;
}

const CommonModal: React.FC<CommonModalProps & ModalProps> = forwardRef((props, ref) => {
	const [form] = Form.useForm();
	const [loading, setLoading] = useState<boolean>(false);

	useImperativeHandle(ref, () => ({ form }));

	function hideModal() {
		form.resetFields();
		props?.close?.();
	}
	function onFinish(values: any) {
		setLoading(true);
		if (props.submitDraft) values = form.getFieldsValue();
		props?.onSubmit?.(values, () => setLoading(false), hideModal);
	}
	useEffect(() => {
		if (props.open) {
			form.setFieldsValue(props.initFormData || {});
		}
	}, [props.open]);
	return (
		<Modal onCancel={hideModal} width={props.width || 1100} destroyOnClose={true} centered footer={null} {...props}>
			<Form form={form} labelCol={{ span: 10 }} wrapperCol={{ span: 14 }} {...(props.formSetting || {})} onFinish={onFinish}>
				{props.children}
				{props.hideFooter ? null : (
					<div className="flex justify-end">
						<Space align="end">
							<Button type="default" onClick={hideModal}>
								取消
							</Button>

							{props.submitDraft && !props.hideSubmit ? (
								<Button type="primary" onClick={onFinish} loading={loading}>
									提交
								</Button>
							) : !props.hideSubmit ? (
								<Button type="primary" htmlType="submit" loading={loading}>
									提交
								</Button>
							) : null}
						</Space>
					</div>
				)}
			</Form>
		</Modal>
	);
});

export default CommonModal;
